package com.fzkj.bio.fileupload;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;

/**
 * 处理客户端请求的线程
 */
public class ServerReadThread implements Runnable {
    private Socket socket;

    public ServerReadThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        OutputStream os = null;
        try {
            // 得到一个数据输入流
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            // 读取文件后缀
            String suffix = dis.readUTF();
            // 定义一个文件输出流把客户端传过来的文件保存到磁盘
            os = new FileOutputStream("E:\\upload\\"
            + UUID.randomUUID().toString() + suffix);
            byte[] buffer = new byte[1024];
            int len;
            while((len = dis.read(buffer)) > 0){
                os.write(buffer, 0, len);
            }
            os.flush();
            System.out.println("文件保存成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
